#pragma once
#include <iostream>
#include <vector>
#include <cstdint>
#include <algorithm>
#include <cassert>
#include <cstring>
#include <ctime>
#include <cstdio>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
#include <memory>
#include <functional>
#include <sys/epoll.h>
#include <unordered_map>
#include <thread>
#include <mutex>
#include <sys/eventfd.h>
#include <sys/timerfd.h>
#include <any>
#include <bits/shared_ptr.h>
#include <mutex>
#include <condition_variable>
#include <pthread.h>

#define info 0
#define debug 1
#define err 2
#define defalut_level err
#define LOG(level, format, ...)                                                                                        \
    do                                                                                                                 \
    {                                                                                                                  \
        time_t t = time(nullptr);                                                                                      \
        if (level < defalut_level)                                                                                     \
            break;                                                                                                     \
        struct tm *ltm = localtime(&t);                                                                                \
        char ti[32] = {0};                                                                                             \
        strftime(ti, 31, "%H:%M:%S", ltm);                                                                             \
        fprintf(stdout, "[%p][%s][%s:%d]" format "\n", (void *)pthread_self(), ti, __FILE__, __LINE__, ##__VA_ARGS__); \
    } while (0)
#define INFO_LOG(format, ...) LOG(info, format, ##__VA_ARGS__)
#define DEBUG_LOG(format, ...) LOG(debug, format, ##__VA_ARGS__)
#define ERROR_LOG(format, ...) LOG(err, format, ##__VA_ARGS__)

#define buffer_default 1024
class Buffer
{
public:
    Buffer() : _buffer(buffer_default) {}
    char *Begin()
    {
        return &*_buffer.begin();
    }
    // 获取当前写入地址
    char *Write_Position()
    {
        return Begin() + _writer_idx;
    }
    // 获取当前读取地址
    char *Read_Position()
    {
        return Begin() + _reader_idx;
    }
    // 获取缓冲区末尾空闲空间地址大小
    uint64_t TailIdleSize()
    {
        return _buffer.size() - _writer_idx;
    }
    // 获取缓冲区起始空闲空间地址大小
    uint64_t HeadIdleSize()
    {
        return _reader_idx;
    }
    // 获取可读数据大小
    uint64_t ReadAbleSize()
    {
        return _writer_idx - _reader_idx;
    }
    // 将读偏移向后移动
    void MoveReadOffset(uint64_t len)
    {
        if (len == 0)
            return;
        assert(len <= ReadAbleSize());
        _reader_idx += len;
    }
    // 将写偏移向后移动
    void MoveWriteOffset(uint64_t len)
    {
        assert(len <= TailIdleSize());
        _writer_idx += len;
    }
    // 确保可写空间足够（空间不够：前移或扩容）
    void EnsureWriteSpace(uint64_t size)
    {
        if (TailIdleSize() >= size)
            return;
        if (TailIdleSize() + HeadIdleSize() >= size)
        {
            int rsz = ReadAbleSize();
            std::copy(Read_Position(), Read_Position() + rsz, Begin());
            _writer_idx = rsz;
            _reader_idx = 0;
        }
        else
            _buffer.resize(_writer_idx + size);
    }
    // 写入数据
    void Write(const void *date, uint64_t len)
    {
        if (len == 0)
            return;
        EnsureWriteSpace(len);
        const char *d = (const char *)date;
        std::copy(d, d + len, Write_Position());
        //_writer_idx+=len;
    }
    void WriteAndPush(const void *date, uint64_t len)
    {
        Write(date, len);
        MoveWriteOffset(len);
    }
    void WriteString(const std::string &data)
    {
        Write(data.c_str(), data.size());
    }
    void WriteStringAndPush(const std::string &data)
    {
        WriteString(data);
        MoveWriteOffset(data.size());
    }
    void WriteBuffer(Buffer &data)
    {
        Write(data.Read_Position(), data.ReadAbleSize());
    }
    void WriteBufferAndPush(Buffer &data)
    {
        WriteBuffer(data);
        MoveWriteOffset(data.ReadAbleSize());
    }
    // 读取数据
    void Read(void *buf, uint64_t len)
    {
        assert(len <= ReadAbleSize());
        std::copy(Read_Position(), Read_Position() + len, (char *)buf);
        //_reader_idx+=len;
    }
    void ReadAndPop(void *buf, uint64_t len)
    {
        Read(buf, len);
        MoveReadOffset(len);
    }
    std::string ReadAsStringAndPop(uint64_t len)
    {
        std::string str = ReadAsString(len);
        MoveReadOffset(len);
        return str;
    }
    std::string ReadAsString(uint64_t len)
    {
        assert(len <= ReadAbleSize());
        std::string str;
        str.resize(len);
        Read(&str[0], len);
        return str;
    }
    // 清空缓冲区
    void Clear()
    {
        _reader_idx = 0;
        _writer_idx = 0;
    }
    char *FindCRLF() // 返回换行字符的位置
    {
        void *res = memchr(Read_Position(), '\n', ReadAbleSize());
        return (char *)res;
    }
    std::string Getline()
    {
        char *pos = FindCRLF();
        if (pos == nullptr)
            return "";
        return ReadAsString(pos - Read_Position() + 1); // 连换行字符一起取出来
    }
    std::string GetlineAndPop()
    {
        std::string str = Getline();
        MoveReadOffset(str.size());
        return str;
    }

private:
    std::vector<char> _buffer;
    uint64_t _reader_idx = 0; // 读偏移
    uint64_t _writer_idx = 0; // 写偏移
};

#define MAX_LISTEN 1024
class Socket
{
public:
    Socket() : _sockfd(-1) {}
    Socket(int fd) : _sockfd(fd) {}
    ~Socket() {}
    int Fd()
    {
        return _sockfd;
    }
    bool Create()
    {
        _sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); // 最后一个参数为TCP协议
        //_sockfd=socket(AF_INET,SOCK_STREAM,0);
        if (_sockfd < 0)
        {
            ERROR_LOG("create socket fail");
            return false;
        }
        return true;
    }
    bool Bind(const std::string &ip, uint16_t port)
    {
        struct sockaddr_in addr;
        memset(&addr, 0, sizeof(addr));
        addr.sin_family = AF_INET;
        addr.sin_port = htons(port);
        addr.sin_addr.s_addr = inet_addr(ip.c_str());
        socklen_t len = sizeof(addr);
        int ret = bind(_sockfd, (struct sockaddr *)&addr, len);
        if (ret < 0)
        {
            ERROR_LOG("bind fail");
            return false;
        }
        return true;
    }
    bool Listen(int backlog = MAX_LISTEN)
    {
        int ret = listen(_sockfd, backlog);
        if (ret < 0)
        {
            ERROR_LOG("listen fail");
            return false;
        }
        return true;
    }
    bool Connect(const std::string &ip, uint16_t port)
    {
        struct sockaddr_in addr;
        memset(&addr, 0, sizeof(addr));
        addr.sin_family = AF_INET;
        addr.sin_port = htons(port);
        addr.sin_addr.s_addr = inet_addr(ip.c_str());
        socklen_t len = sizeof(addr);
        int ret = connect(_sockfd, (struct sockaddr *)&addr, len);
        if (ret < 0)
        {
            ERROR_LOG("connect fail");
            return false;
        }
        return true;
    }
    int Accept()
    {
        struct sockaddr_in addr;
        socklen_t len = sizeof(addr);
        int fd = accept(_sockfd, (struct sockaddr *)&addr, &len);
        if (fd < 0)
        {
            ERROR_LOG("accept fail:%s,%d", strerror(errno), _sockfd);
            return -1;
        }
        return fd;
    }
    ssize_t Recv(void *buf, size_t len, int flag = 0) // 默认阻塞操作
    {
        ssize_t size = recv(_sockfd, buf, len, flag);
        if (size <= 0)
        {
            // EAGAIN说明当前套接字是非阻塞，缓冲区里没有数据，EAGAIN才会被设置
            // EINTR说明recv的阻塞状态被信号打断
            if (errno == EAGAIN || errno == EINTR)
                return 0; // 表示这次接收没有接收到，但是连接并没有出错
            //ERROR_LOG("recv fail");
            return -1;
        }
        return size;
    }
    ssize_t NonBlockRecv(void *buf, size_t len) // 非阻塞接收
    {
        return Recv(buf, len, MSG_DONTWAIT); // MSG_DONTWAIT为非阻塞标志，表示当前接受为非阻塞，没有数据就是报错返回
    }
    ssize_t Send(const void *buf, size_t len, int flag = 0) // 阻塞发送
    {
        if (len == 0)
            return 0;
        ssize_t size = send(_sockfd, buf, len, flag);
        if (size < 0)
        {
            if (errno == EAGAIN || errno == EINTR)
                return 0; // 表示这次接收没有接收到，但是连接并没有出错
            ERROR_LOG("send fail");
            return -1;
        }
        return size;
    }
    ssize_t NonBlockSend(void *buf, size_t len) // 阻塞发送
    {
        return Send(buf, len, MSG_DONTWAIT);
    }
    void Close()
    {
        if (_sockfd != -1)
            close(_sockfd);
        _sockfd = -1;
    }
    bool CreateServer(uint16_t port, const std::string &ip = "0.0.0.0", bool block_flag = false)
    {
        if (Create() == false)
            return false;
        if (block_flag)
            SetNonBlock();
        ReuseAddress();
        if (Bind(ip, port) == false)
            return false;
        if (Listen() == false)
            return false;

        return true;
    }
    bool CreateClient(uint16_t port, const std::string &ip)
    {
        if (Create() == false)
            return false;
        if (Connect(ip, port) == false)
            return false;
        return true;
    }
    void ReuseAddress() // 设置监听套接字可重用
    {
        int val = 1;
        // 第二个参数为,level，设置为套接字等级
        // 第三个参数为设置选项，设置为可重用地址与端口
        // setsockopt函数写进去的是“最终值”，如果想要提取原来的需要使用getsockopt
        setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &val, sizeof(val));
    }
    void SetNonBlock() // 设置套接字属性非阻塞
    {
        int flag = fcntl(_sockfd, F_GETFL, 0);
        fcntl(_sockfd, F_SETFL, flag | O_NONBLOCK);
    }

private:
    int _sockfd;
};

class Poller;
class EventLoop;

class Channel
{
public:
    using EventCallback = std::function<void()>; // 事件回调
    Channel(int fd, EventLoop *poller) : _fd(fd), _poller(poller), _events(0), _revents(0) {}
    int Fd() { return _fd; }
    // 获取想要监控的事件
    uint32_t Events() { return _events; }
    // 文件描述符实际就绪的事件通过该接口进行设置
    void SetRevents(uint32_t events) { _revents = events; }
    // 设置可读事件回调
    void SetReadCallback(const EventCallback &cb) { _read_callback = cb; }
    // 设置可写事件回调
    void SetWriteCallback(const EventCallback &cb) { _write_callback = cb; }
    // 设置错误事件回调
    void SetErrorCallback(const EventCallback &cb) { _error_callback = cb; }
    // 设置连接断开事件回调
    void SetCloseCallback(const EventCallback &cb) { _close_callback = cb; }
    // 设置任意事件回调
    void SetEventCallback(const EventCallback &cb) { _event_callback = cb; }
    // 当前事件是否监控了可读
    bool Readable() { return _events & EPOLLIN; }
    // 当前事件是否监控了可写
    bool Writeable() { return _events & EPOLLOUT; }
    // 启动可读监控
    void EnableRead()
    {
        _events |= EPOLLIN;
        Update();
    }
    // 启动可写监控
    void EnableWrite()
    {
        _events |= EPOLLOUT;
        Update();
    }
    // 关闭可读监控
    void DisableRead()
    {
        _events &= ~EPOLLIN;
        Update();
    }
    // 关闭可写监控
    void DisableWrite()
    {
        _events &= ~EPOLLOUT;
        Update();
    }
    // 关闭所有事件监控
    void DisableAll() { _events = 0; }
    // 移除监控
    void Remove();
    // 将channel放到poller监控中
    void Update();
    // 事件处理，一旦连接触发了事件就调用该接口，怎么处理自己决定
    void Handle_Event()
    {
        if (((_revents & EPOLLIN) || (_revents & EPOLLRDHUP) || (_revents & EPOLLPRI))) // in是可读，rdhup是对端关闭,pri是紧急可读
        {
            // 不管发送什么事件发生，都要调用的回调函数
            if (_event_callback)
                _event_callback();
            if (_read_callback)
                _read_callback();
        }
        // 有可能会释放连接的操作，一次只处理一个
        if ((_revents & EPOLLOUT)) // 可写
        {
            if (_event_callback)
                _event_callback();
            if (_write_callback)
                _write_callback();
        }
        else if ((_revents & EPOLLERR)) // 出错
        {
            // 一旦连接被释放就没法执行任意事件回调，因此要先执行任意事件回调
            if (_event_callback)
                _event_callback();
            if (_error_callback)
                _error_callback();
        }
        else if ((_revents & EPOLLHUP)) // 管道读端关闭
        {
            if (_event_callback)
                _event_callback();
            if (_close_callback)
                _close_callback();
        }
    }

private:
    int _fd;
    EventLoop *_poller;
    uint32_t _events;              // 当前需要监控的事件
    uint32_t _revents;             // 当前连接触发的事件
    EventCallback _read_callback;  // 可读事件回调
    EventCallback _write_callback; // 可写事件回调
    EventCallback _error_callback; // 错误事件回调
    EventCallback _close_callback; // 连接断开事件回调
    EventCallback _event_callback; // 任意事件回调
};

#define MAX_POLLEVENT 1024
class Poller
{
public:
    Poller()
    {
        _epfd = epoll_create(MAX_POLLEVENT); // 这个参数现在已经被忽略了，但必须输入一个大于0的值
        if (_epfd < 0)
        {
            ERROR_LOG("create epoll fail");
            abort();
        }
    }
    int Fd()
    {
        return _epfd;
    }
    // 添加，修改监控
    void UpdateEvent(Channel *channel)
    {
        bool ret = HashChannel(channel);
        if (ret == false) // 说明不存在，添加
        {
            _channels[channel->Fd()] = channel;
            Update(channel, EPOLL_CTL_ADD);
        }
        else
            Update(channel, EPOLL_CTL_MOD);
    }
    // 移除监控
    void RemoveEvent(Channel *channel)
    {
        auto it = _channels.find(channel->Fd());
        if (it != _channels.end())
            _channels.erase(channel->Fd());
        Update(channel, EPOLL_CTL_DEL);
    }
    // 开始监控
    void Poll(std::vector<Channel *> *active)
    {
        // 第三个参数必须大于0并且小于等于第二个参数数组的长度，最后一个参数为等待时间（单位毫秒），设置为-1即阻塞
        // 返回时填入数组的不是按照事件分，而是按照文件描述符分
        int nfds = epoll_wait(_epfd, _evs, MAX_POLLEVENT, -1); // 返回值为就绪的文件描述符个数
        if (nfds < 0)
        {
            if (errno == EINTR) // 表示阻塞被信号打断
                return;
            ERROR_LOG("epoll_wait error:%s", strerror(errno));
            abort();
        }
        for (int i = 0; i < nfds; ++i)
        {
            auto iter = _channels.find(_evs[i].data.fd);
            assert(iter != _channels.end());
            iter->second->SetRevents(_evs[i].events);
            active->emplace_back(iter->second);
        }
    }

private:
    // 对epoll的直接操作
    void Update(Channel *channel, int op)
    {
        int fd = channel->Fd();
        struct epoll_event ev;
        ev.data.fd = fd;
        ev.events = channel->Events();
        int ret = epoll_ctl(_epfd, op, fd, &ev);
        if (ret < 0)
        {
            ERROR_LOG("epoll_ctl fail");
            abort(); // 退出程序
        }
    }
    // 判断一个 channel是否添加了监控
    bool HashChannel(Channel *channel)
    {
        int fd = channel->Fd();
        auto it = _channels.find(fd);
        if (it == _channels.end())
            return false;
        return true;
    }

private:
    int _epfd;
    std::unordered_map<int, Channel *> _channels; // 用于保存就绪的描述符
    struct epoll_event _evs[MAX_POLLEVENT];
};

using Task_func = std::function<void()>;
using Release_Func = std::function<void()>;

class TimerTask
{
public:
    TimerTask(uint64_t id, uint32_t timeout, const Task_func &cb) : _id(id), _timeout(timeout), _task(cb) {}
    void Set_Release(const Release_Func &release)
    {
        _release = release;
    }
    ~TimerTask()
    {
        if (_canceled == false)
            _task();
        _release();
    }
    uint32_t GetTimeOut()
    {
        return _timeout;
    }
    void Cancel()
    {
        _canceled = true;
    }

private:
    uint64_t _id;      // 唯一的定时器id
    uint32_t _timeout; // 定时器超时时间
    Task_func _task;
    Release_Func _release;
    bool _canceled = false;
};

class TimerWheel
{
public:
    // weakptr与sharedptr不能类型强转，sharedptr可以用来构造weakptr，因为weakptr是作为观察者
    // weakptr不能用来构造sharedptr，但是可以使用对应的lock接口来获取weakptr观察的sharedptr对象
    using shared_task = std::shared_ptr<TimerTask>;
    using weak_task = std::weak_ptr<TimerTask>;
    static int Creadte_TimerFd()
    {
        // 设置为相对开机时间
        int timerfd = timerfd_create(CLOCK_MONOTONIC, 0);
        if (timerfd < 0)
        {
            ERROR_LOG("create timerfd fail");
            abort();
        }
        struct itimerspec itime; // 间隔与初始等待时间均设置为1
        itime.it_interval.tv_sec = 1;
        itime.it_interval.tv_nsec = 0;
        itime.it_value.tv_sec = 1;
        itime.it_value.tv_nsec = 0;
        timerfd_settime(timerfd, 0, &itime, nullptr);
        return timerfd;
    }
    void ReadTimerfd()
    {
        uint64_t times;
        int ret = read(_timer_fd, &times, 8);
        if (ret < 0)
        {
            ERROR_LOG("read error");
            abort();
        }
    }
    void OnTime()
    {
        ReadTimerfd();
        RunTask();
    }
    TimerWheel(EventLoop *loop) : _loop(loop), _timer_fd(Creadte_TimerFd()), _timer_channel(new Channel(_timer_fd, _loop)),
                                  _capacity(60), _tick(0), _wheel(_capacity)
    {
        _timer_channel->SetReadCallback(std::bind(&TimerWheel::OnTime, this));
        _timer_channel->EnableRead();
    }

    void Time_Add(uint64_t id, uint32_t timeout, const Task_func &cb);

    void TimeRefresh(uint64_t id);

    // 这个接口存在线程安全问题，需要在对应的eventloop中进行
    bool HasTimer(uint64_t id)
    {
        return _map.count(id);
    }

    void RunTask()
    {
        _tick = (_tick + 1) % _capacity;
        _wheel[_tick].clear(); // clear接口可以释放数组中的所有对象
    }
    void CancleTask(uint64_t id);

private:
    void CancleTaskInLoop(uint64_t id)
    {
        if (_map.count(id))
            _map[id].lock()->Cancel();
    }
    void TimeRefreshInLoop(uint64_t id)
    {
        shared_task new_task(_map[id].lock());
        _wheel[(_tick + new_task->GetTimeOut()) % _capacity].emplace_back(new_task);
    }
    void Reomve_Timer(uint64_t id)
    {
        auto timers = _map.find(id);
        if (timers != _map.end())
            _map.erase(timers);
    }
    void time_add_inloop(uint64_t id, uint32_t timeout, const Task_func &cb)
    {
        shared_task new_task(new TimerTask(id, timeout, cb));
        auto remove = std::bind(&TimerWheel::Reomve_Timer, this, id);
        new_task->Set_Release(remove);
        _map[id] = weak_task(new_task);
        _wheel[(_tick + new_task->GetTimeOut()) % _capacity].emplace_back(new_task);
    }

private:
    EventLoop *_loop;
    int _timer_fd; // 定时器文件描述符，可读事件回调就是读取计数器，执行可读任务
    std::unique_ptr<Channel> _timer_channel;
    int _capacity;
    int _tick;
    std::vector<std::vector<shared_task>> _wheel;
    std::unordered_map<uint64_t, weak_task> _map;
};

class EventLoop
{
public:
    using Functor = std::function<void()>;
    EventLoop() : _thread_id(std::this_thread::get_id()),
                  _event_fd(Create_Eventfd()),
                  _event_channel(new Channel(_event_fd, this)),
                  _timer_wheel(this)
    {
        // 通过将event放入监控中，这样有事件到来时，就可以通过eventfd直接唤醒epoll
        _event_channel->SetReadCallback(std::bind(&EventLoop::ReadEventfd, this));
        _event_channel->EnableRead();
    }
    // 判断将要执行的任务是否处在当前线程中，是则执行，不是则放入任务队列
    void RunInLoop(const Functor &cb)
    {
        if (Is_Loop())
            cb();
        else
            QueueInLoop(cb);
    }
    // 将操作压入任务队列
    void QueueInLoop(const Functor &cb)
    {
        {
            std::unique_lock<std::mutex> _lock(_mutex);
            _tasks.emplace_back(cb);
        }
        WeakUpEventfd(); // 此时已经有任务需要执行了，为了防止在epoll那里阻塞导致无法执行任务，这里直接唤醒
    }
    void AssertInLoop()
    {
        assert(std::this_thread::get_id() == _thread_id);
    }
    // 判断当前线程是否是EventLoop对应线程
    bool Is_Loop()
    {
        return std::this_thread::get_id() == _thread_id;
    }
    // 添加/修改事件监控
    void UpdateEvent(Channel *channel)
    {
        _poller.UpdateEvent(channel);
    }
    // 移除事件监控
    void RemoveEvent(Channel *channel)
    {
        _poller.RemoveEvent(channel);
    }
    // 事件监控->就绪任务处理->执行任务
    void Start()
    {
        while (1)
        {
            // 这里执行两中任务，一个是监控的文件描述符的任务，一个是外部添加的任务
            // 事件监控
            std::vector<Channel *> actives;
            _poller.Poll(&actives); // 有可能会等待事件发生一直阻塞
            // 就绪任务处理
            for (auto &channel : actives)
                channel->Handle_Event();
            // 执行外部任务
            RunAllTask();
        }
    }

    // 添加定时任务
    void Add_Timer(uint64_t id, uint32_t timeout, const Task_func &cb)
    {
        _timer_wheel.Time_Add(id, timeout, cb);
    }
    void Time_Refresh(uint64_t id)
    {
        _timer_wheel.TimeRefresh(id);
    }
    void Time_Cancle(uint64_t id)
    {
        _timer_wheel.CancleTask(id);
    }
    bool HashTimer(uint64_t id)
    {
        return _timer_wheel.HasTimer(id);
    }

public:
    // 执行任务池中的所有任务
    void RunAllTask()
    {
        std::vector<Functor> tasks;
        {
            std::unique_lock<std::mutex> _lock(_mutex);
            tasks.swap(_tasks);
        }
        for (auto &f : tasks)
            f();
            
        return;
    }
    static int Create_Eventfd()
    {
        int fd = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
        if (fd < 0)
        {
            ERROR_LOG("create evfd fail");
            abort(); // 让程序异常退出
            return -1;
        }
        return fd;
    }
    void ReadEventfd()
    {
        uint64_t val = 1;
        int ret = read(_event_fd, &val, sizeof(val));
        if (ret < 0)
        {
            // EINTR表示被信号打断，EAGAIN表示无数据可读，主要是非阻塞读取,返回-1
            if (errno == EINTR || errno == EAGAIN)
                return;
            ERROR_LOG("read eventfd fail");
            abort();
        }
    }
    void WeakUpEventfd()
    {
        uint64_t val = 1;
        int ret = write(_event_fd, &val, sizeof(val));
        if (ret < 0)
        {
            if (errno == EINTR)
                return;
            ERROR_LOG("write eventfd fail");
            abort();
        }
    }

private:
    std::thread::id _thread_id;
    int _event_fd;
    std::unique_ptr<Channel> _event_channel;
    Poller _poller;
    std::vector<Functor> _tasks; // 任务队列
    std::mutex _mutex;
    TimerWheel _timer_wheel; // 定时器模块
};

class LoopThread
{
public:
    LoopThread() : _thread(&LoopThread::ThreadEntry, this), _loop(nullptr) {}
    EventLoop *GetLoop()
    {
        EventLoop *loop = nullptr;
        {
            std::unique_lock<std::mutex> _lock(_mutex); // 加锁
            _cond.wait(_lock, [&]()
                       { return _loop != nullptr; }); // loop为空就一直阻塞，等待唤醒
            loop = _loop;
        }
        return loop;
    }

private:
    // 线程入口函数
    void ThreadEntry()
    {
        EventLoop loop;
        {
            std::unique_lock<std::mutex> _lock(_mutex); // 加锁
            _loop = &loop;
            _cond.notify_all();
        }
        loop.Start();
    }

private:
    std::mutex _mutex;
    std::condition_variable _cond;
    std::thread _thread;
    EventLoop *_loop;
};

class Acceptor
{
public:
    using AcceptCallback = std::function<void(int)>;
    // 启动可读事件监控必须在构造并设置完回调函数之后，否则可能还未设置回调函数就立即有事件
    Acceptor(EventLoop *loop, int port) : _loop(loop), _socket(CreateServer(port)), _channel(_socket.Fd(), loop)
    {
        _channel.SetReadCallback(std::bind(&Acceptor::HandleRead, this));
        //_channel.EnableRead();
    }
    void SetReadCallBack(const AcceptCallback &cb)
    {
        _acceptcallback = cb;
    }
    void Listen()
    {
        _channel.EnableRead();
    }

private:
    int CreateServer(int port)
    {
        bool ret = _socket.CreateServer(port);
        assert(ret == true);
        return _socket.Fd();
    }
    void HandleRead()
    {
        int newfd = _socket.Accept();
        if (newfd < 0)
            return;
        if (_acceptcallback)
            _acceptcallback(newfd);
    }
    EventLoop *_loop;
    Socket _socket;
    Channel _channel;
    AcceptCallback _acceptcallback;
};

// EventLoop类定义在channel的下方，只声明类对象是找不到类的成员方法的，所以要在下面实现channel方法
void Channel::Remove() { _poller->RemoveEvent(this); }
void Channel::Update() { _poller->UpdateEvent(this); }
void TimerWheel::Time_Add(uint64_t id, uint32_t timeout, const Task_func &cb)
{
    // 定时任务可能是来自多个线程的，并可能涉及到连接，因此要考虑线程安全问题
    // 不想加锁，就交给同一个线程进行操作
    _loop->RunInLoop(std::bind(&TimerWheel::time_add_inloop, this, id, timeout, cb));
    // 同时可以绑定类的私有成员是因为在类外是获取不到成员函数的地址的，因此在类外既无法绑定，有不能调用私有成员函数
    // 但是在类内可以获取到地址，因此可以调用，也可以绑定
}

void TimerWheel::TimeRefresh(uint64_t id)
{
    _loop->RunInLoop(std::bind(&TimerWheel::TimeRefreshInLoop, this, id));
}

void TimerWheel::CancleTask(uint64_t id)
{
    _loop->RunInLoop(std::bind(&TimerWheel::CancleTaskInLoop, this, id));
}

enum Connstatu
{
    DISCONNECTED,
    CONNECTING,
    CONNECTED,
    DISCONNECTING
};

class Connection;
using PtrConnection = std::shared_ptr<Connection>;

class Connection : public std::enable_shared_from_this<Connection>
{
public:
    using ConnectedCallback = std::function<void(const PtrConnection &)>;
    using MessageCallback = std::function<void(const PtrConnection &, Buffer *)>;
    using CloseCallback = std::function<void(const PtrConnection &)>;
    using AnyEventCallback = std::function<void(const PtrConnection &)>;

    Connection(EventLoop *loop, uint64_t id, int sockfd)
        : _loop(loop), _id(id), _sockfd(sockfd), _enable_inactive_release(false),
          _statu(CONNECTING), _socket(sockfd), _channel(sockfd, loop)
    {
        _channel.SetReadCallback(std::bind(&Connection::HandleRead, this));
        _channel.SetWriteCallback(std::bind(&Connection::HandleWrite, this));
        _channel.SetCloseCallback(std::bind(&Connection::HandleClose, this));
        _channel.SetErrorCallback(std::bind(&Connection::HandleError, this));
        _channel.SetEventCallback(std::bind(&Connection::HandleEvent, this));
    }
    ~Connection()
    {
        DEBUG_LOG("release connection:%p", this);
    }
    int Fd() { return _sockfd; }
    int Id() { return _id; }
    bool BeConnected() { return _statu == CONNECTED; }
    Connstatu Statu(){return _statu;}
    // 设置上下文
    void SetContext(std::any context) { _context = context; }
    // 获取上下文
    std::any *GetContext() { return &_context; }
    void SetConnectedCallback(const ConnectedCallback &cb) { _connect_callback = cb; }
    void SetMessageCallback(const MessageCallback &cb) { _message_callback = cb; }
    void SetCloseCallback(const CloseCallback &cb) { _close_callback = cb; }
    void SetAnyEventCallback(const AnyEventCallback &cb) { _event_callback = cb; }
    void SetSrvCloseCallback(const CloseCallback &cb) { _close_server_callback = cb; }
    void Send(const char *data, size_t len)
    {
        Buffer buf;
        buf.WriteAndPush(data, len);
        _loop->RunInLoop(std::bind(&Connection::SendInLoop, this, buf));
    }
    void ShutDown()
    {
        _loop->RunInLoop(std::bind(&Connection::ShutDownInLoop, this));
    }
    void Release()
    {
        _loop->QueueInLoop(std::bind(&Connection::ReleaseInLoop, this));
    }
    void EnableInactiveRelease(int sec)
    {
        _loop->RunInLoop(std::bind(&Connection::EnableInactiveReleaseInLoop, this, sec));
    }
    void CancelInactiveRelease()
    {
        _loop->RunInLoop(std::bind(&Connection::CancelInactiveReleaseInLoop, this));
    }
    // 建立连接就绪后，进行channel回调设置，启动读监控调用ConnectedCallback
    void Established()
    {
        _loop->RunInLoop(std::bind(&Connection::EstablishedInLoop, this));
    }
    // 切换协议，重置上下文以及处理函数
    void Upgrade(const std::any &context, const ConnectedCallback &conn, const MessageCallback &message,
                 const CloseCallback &close, const AnyEventCallback &event)
    {
        _loop->RunInLoop(std::bind(&Connection::UpgradeInLoop, this, context, conn, message, close, event));
    }

private:
    void HandleRead() // 描述符可读事件触发后调用的回调函数
    {
        char buffer[65535];
        int ret = _socket.NonBlockRecv(buffer, sizeof(buffer) - 1);
        if (ret < 0) // 出错了
            return ShutDownInLoop();
        _in_buffer.WriteAndPush(buffer, ret);
        // shared_from_this()从当前对象自身获取一个shared_ptr管理对象
        // 但是需要继承enable_shared_from_this类
        if (_in_buffer.ReadAbleSize() > 0)
            return _message_callback(shared_from_this(), &_in_buffer);
    }
    void HandleWrite() // 可写事件
    {
        int ret = _socket.NonBlockSend(_out_buffer.Read_Position(), _out_buffer.ReadAbleSize());
        if (ret < 0) // 出错了
        {
            if (_in_buffer.ReadAbleSize() > 0)
            {
                _message_callback(shared_from_this(), &_in_buffer);
            }
            return Release();
        }
        _out_buffer.MoveReadOffset(ret);
        if (_out_buffer.ReadAbleSize() == 0)
        {
            _channel.DisableWrite();
            if (_statu == DISCONNECTING)
                return Release(); // 如果当前是连接待关闭状态并且数据都读取完了则直接释放
        }
    }
    void HandleError() // 错误
    {
        HandleClose();
    }
    // 挂断
    void HandleClose()
    {
        // 一旦连接挂断就什么也做不了了，因此有数据就处理一下
        if (_in_buffer.ReadAbleSize() > 0)
        {
            _message_callback(shared_from_this(), &_in_buffer);
        }
        return Release();
    }
    void HandleEvent() // 任意
    {
        if (_enable_inactive_release)
            _loop->Time_Refresh(_id);
        if (_event_callback)
            _event_callback(shared_from_this());
    }
    // 这个有可能是临时空间，因此拷贝一份
    void SendInLoop(Buffer buf)
    {
        if (_statu == DISCONNECTED)
            return;
        _out_buffer.WriteBufferAndPush(buf);
        if (_channel.Writeable() == false)
            _channel.EnableWrite();
    }
    // 这个关闭操作并非实际的连接释放操作，需要判断是否有数据待发送
    void ShutDownInLoop()
    {
        _statu = DISCONNECTING;            // 设置连接位半关闭状态
        if (_in_buffer.ReadAbleSize() > 0) // 用户有可能压根不处理数据或者数据处理不完
            if (_message_callback)
                _message_callback(shared_from_this(), &_in_buffer);
        if (_out_buffer.ReadAbleSize() > 0)
            if (_channel.Writeable() == false)
                _channel.EnableWrite();
        if (_out_buffer.ReadAbleSize() == 0) // 因此我们只要发送完毕就关闭连接
            Release();
    }
    void EnableInactiveReleaseInLoop(int sec)
    {
        // 设置为非活跃销毁
        _enable_inactive_release = true;
        // 有则刷新
        if (_loop->HashTimer(_id))
            _loop->Time_Refresh(_id);
        // 没有则创建
        else
            _loop->Add_Timer(_id, sec, std::bind(&Connection::Release, this));
    }
    void CancelInactiveReleaseInLoop()
    {
        // 与上面反过来即可
        _enable_inactive_release = false;
        if (_loop->HashTimer(_id))
            _loop->Time_Cancle(_id);
    }
    // 必须要保证线程安全
    void UpgradeInLoop(const std::any &context, const ConnectedCallback &conn, const MessageCallback &message,
                       const CloseCallback &close, const AnyEventCallback &event)
    {
        _loop->AssertInLoop();
        _context = context;
        _connect_callback = conn;
        _message_callback = message;
        _close_callback = close;
        _event_callback = event;
    }
    void ReleaseInLoop() // 实际的释放接口
    {
        // 修改连接状态位连接释放状态
        _statu = DISCONNECTED;
        // 移除连接事件监控
        _channel.Remove();
        // 关闭描述符
        _socket.Close();
        // 如果定时器中还有定时销毁任务则移除
        if (_loop->HashTimer(_id))
            _loop->Time_Cancle(_id);
        // 调用关闭回调函数，先调用用户的，避免先移除服务器管理信息导致出错
        if (_close_callback)
            _close_callback(shared_from_this());
        if (_close_server_callback)
            _close_server_callback(shared_from_this());
    }
    void EstablishedInLoop() // 连接获取之后所处的状态下要进行的各种设置
    {
        assert(_statu == CONNECTING);
        _statu = CONNECTED; // 当前函数执行完毕则进入连接完成状态
        _channel.EnableRead();
        if (_connect_callback)
            _connect_callback(shared_from_this());
    }

private:
    EventLoop *_loop;
    uint64_t _id; // 连接的唯一id，用于连接管理与查找（与定时器共用id）
    int _sockfd;
    bool _enable_inactive_release;
    Connstatu _statu;
    Socket _socket;
    Channel _channel;
    Buffer _in_buffer;  // 输入缓冲区，存放从socket中获取的数据
    Buffer _out_buffer; // 输出缓冲区，存放发送给对端的数据
    std::any _context;
    ConnectedCallback _connect_callback;
    MessageCallback _message_callback;
    CloseCallback _close_callback;
    // 组件内的关闭连接回调，一旦某个连接关闭，要从管理的地方移除掉
    CloseCallback _close_server_callback;
    AnyEventCallback _event_callback;
};

class LoopThreadPool
{
public:
    LoopThreadPool(EventLoop *loop) : _next_idx(0), thread_count(0), _baseloop(loop) {}
    // 设置线程数量
    void SetThreadCount(int count) { thread_count = count; }
    // 创建从属线程
    void Create()
    {
        if (thread_count > 0)
        {
            _threads.resize(thread_count);
            _loops.resize(thread_count);
            for (int i = 0; i < thread_count; ++i)
            {
                _threads[i] = new LoopThread();
                _loops[i] = _threads[i]->GetLoop();
            }
        }
    }
    EventLoop *NextLoop()
    {
        if (thread_count == 0)
            return _baseloop;
        _next_idx = (_next_idx + 1) % thread_count;
        return _loops[_next_idx];
    }

private:
    int _next_idx;
    int thread_count;
    EventLoop *_baseloop;
    std::vector<LoopThread *> _threads;
    std::vector<EventLoop *> _loops;
};

class TcpServer
{
public:
    TcpServer(int port) : _port(port), _time_out(0), _enable_inactive_release(false), _next_id(0),
                          _acceptor(&_baseloop, port), _pool(&_baseloop)
    {
        _acceptor.SetReadCallBack(std::bind(&TcpServer::NewConncetion,this,std::placeholders::_1));
        _acceptor.Listen();
    }
    using ConnectedCallback = std::function<void(const PtrConnection &)>;
    using MessageCallback = std::function<void(const PtrConnection &, Buffer *)>;
    using CloseCallback = std::function<void(const PtrConnection &)>;
    using AnyEventCallback = std::function<void(const PtrConnection &)>;
    using Fucntor = std::function<void()>;

    void SetThreadCount(int count) { _pool.SetThreadCount(count); }
    void SetConnectedCallback(const ConnectedCallback &cb) { _connect_callback = cb; }
    void SetMessageCallback(const MessageCallback &cb) { _message_callback = cb; }
    void SetCloseCallback(const CloseCallback &cb) { _close_callback = cb; }
    void SetAnyEventCallback(const AnyEventCallback &cb) { _event_callback = cb; }
    void EnableInactiveRelease(int sec)
    {
        _enable_inactive_release = true;
        _time_out = sec;
    };
    void RunAfter(const Fucntor &task, int delay) // 添加一个定时任务
    {
        _baseloop.RunInLoop(std::bind(&TcpServer::RunAfterInLoop, this, task, delay));
    }
    void Start()
    {
        _pool.Create();
        _baseloop.Start();
    }

private:
    void RunAfterInLoop(const Fucntor &task, int delay)
    {
        _baseloop.Add_Timer(_next_id++, delay, task);
    }
    void NewConncetion(int fd) // 为新连接创建connection进行管理
    {
        ++_next_id;
        PtrConnection conn(new Connection(_pool.NextLoop(), _next_id, fd));
        conn->SetMessageCallback(_message_callback);
        conn->SetSrvCloseCallback(std::bind(&TcpServer::RemoveConnection,this,std::placeholders::_1));
        conn->SetCloseCallback(_close_callback);
        conn->SetConnectedCallback(_connect_callback);
        conn->SetAnyEventCallback(_event_callback);
        if(_enable_inactive_release)
            conn->EnableInactiveRelease(_time_out); // 启动非活跃销毁功能
        conn->Established();
        _conns[_next_id] = conn;
    }
    void RemoveConnection(const PtrConnection& conn) // 从管理connection的_conns中移除连接信息进行释放
    {
        _baseloop.RunInLoop(std::bind(&TcpServer::RemoveConnectionInLoop,this,conn));
    }
    void RemoveConnectionInLoop(const PtrConnection& conn) // 从管理connection的_conns中移除连接信息进行释放
    {
        int id=conn->Id();
        if(_conns.count(id))
            _conns.erase(id);
    }
private:
    int _port;
    int _time_out;                                      // 非活跃连接统计事件
    bool _enable_inactive_release;                      // 是否启动非活跃连接销毁
    uint64_t _next_id;                                  // 自动增长的id，可用于连接与定时任务
    EventLoop _baseloop;                                // 主线程loop
    Acceptor _acceptor;                                 // 监听套接字管理对象
    LoopThreadPool _pool;                               // 从属线程池
    std::unordered_map<uint64_t, PtrConnection> _conns; // 保存管理所有连接对应的shared_ptr，这里被删除那么某一个连接就被释放
    ConnectedCallback _connect_callback;
    MessageCallback _message_callback;
    CloseCallback _close_callback;
    // 组件内的关闭连接回调，一旦某个连接关闭，要从管理的地方移除掉
    AnyEventCallback _event_callback;
};